const mysql = require('mysql');
// 第一个连接对象
let conn = mysql.createConnection({
	port: '3306',
	user: 'root',
	password: 'root',
	database: 'newsdata',
	host: '127.0.0.1'
});

function query(sql, callback, param) {
	conn = mysql.createConnection(conn.config);
	// 连接数据库
	conn.connect();
	//执行过程
	if (param) {
		conn.query(sql, param, (err, data) => {
			if (err) {
				console.error(err)
			} else {
				callback(data)
			}
		})
	} else {
		conn.query(sql, (err, data) => {
			if (err) {
				console.error(err)
			} else {
				callback(data)
				
			}
		})
	}
	// 断开连接
	conn.end()
}


// 增
function add(param, condition) {
	const sql = `INSERT INTO ${condition}`;
	return new Promise(resolve => {
		//执行过程
		query(sql, data => {
			resolve(data)
		}, param)
	})
}
// 删
function del(condition, table = 'user') {
	const sql = `DELETE FROM ${table} where ${condition}`;
	//执行过程
	return new Promise(resolve => {
		//执行过程
		query(sql, data => {
			resolve(data)
		})
	})
}

// 改
function edit(param, condition, table = 'user') {
	const sql = `UPDATE ${table} SET title=?,date=?,author=?,content=? where ${condition}`;
	//执行过程
	return new Promise(resolve => {
		//执行过程
		query(sql, data => {
			resolve(data)
		}, param)
	})
}

// 完整的表格查询
function search(table = 'user') {
	const sql = `SELECT * FROM ${table} `;
	//执行过程
	return new Promise(resolve => {
		query(sql, data => {
			resolve(data)
		})
	})
}
// 条件查询
function searchBy(condition, table = 'user') {
	const sql = `SELECT * FROM ${table} WHERE ${condition}`;
	//执行过程
	return new Promise(resolve => {
		query(sql, data => {
			resolve(data)
		})
	})
}

function deletedate(id,table){
	const sql = `UPDATE ${table} SET state=? where id=?`;	//执行过程
	return new Promise(resolve => {
		//执行过程
		query(sql,data => {
			resolve(data)
		},[0,id])
	})
 }

module.exports = {
	add,
	del,
	edit,
	search,
	searchBy,
	deletedate
}
